<template>
  <!-- 在你的 WXML 文件中 -->
  <view class="container">
    <scroll-view
      :scroll-y="true"
      style="height: 300px"
      @scroll="scroll"
      :scroll-with-animation="true"
      :scroll-top="scrollTop"
    >
      <view class="item" id="item1">Item 1</view>
      <view class="item" id="item2">Item 2</view>
      <view class="item" id="item">Item 3</view>
      <view class="item" id="item4">Item 4</view>
      <view class="item" id="item5">Item 5</view>
      <view class="item" id="item6">Item 6</view>
      <view class="item" id="item7">Item 7</view>
      <view class="item" id="item8">Item 8</view>
      <view class="item" id="item9">Item 9</view>
      <view class="item" id="item10">Item 10</view>
      <view class="item" id="item10">Item 10</view>
      <view class="item" id="item10">Item 10</view>
      <view class="item" id="item10">Item 10</view>
      <view class="item" id="item10">Item 10</view>
      <view class="item" id="item10">Item 10</view>
      <view class="item" id="item10">Item 10</view>
      <view class="item" id="item10">Item 17</view>
    </scroll-view>
    <button @click="scrollToItem">滚动到 Item 3</button>
  </view>
</template>

<script setup>
import { ref, reactive, nextTick } from "vue";
const scrollTop = ref(0); // 用于存储 scrollTop 的值
const intoView = ref("item1"); // 用于 scroll-view 的 scroll-into-view 属性
const scrollHeight = ref(0);
const old = reactive({ scrollTop: 0 }); // 用于存储 scroll-view 的引用
const scrollToItem = () => {
  // intoView.value = "item3"; // 设置 scroll-into-view 的值为 item3
  // return;
  const query = wx.createSelectorQuery(); // 获取页面元素的查询器
  console.log("query:", query);

  // uni.pageScrollTo({
  //   selector: "#item",
  //   duration: 300,
  //   success: (res) => {
  //     console.log("res:", res);
  //   },
  // });
  // return;
  // wx.pageScrollTo({
  //   // scrollTop: 0, // 计算滚动位置
  //   selector: "#item3", // 滚动到的元素选择器
  //   duration: 300, // 滚动持续时间，单位 ms
  //   success(e) {
  //     console.log("e:", e);
  //   },
  // });
  // return;
  scrollTop.value = old.scrollTop;
  nextTick(() => {
    scrollTop.value = 0;
  });
  query
    .select("#item")
    .boundingClientRect((rect) => {
      console.log("rect:", rect);
      scrollTop.value = 0; // 更新 scrollTop 的值
    })
    .exec();
};
const scroll = (e) => {
  console.log(e);
  // scrollTop.value = e.detail.scrollTop;
  old.scrollTop = e.detail.scrollTop;
  // intoView.value = "item6"; // 清空 scroll-into-view 的值
};
</script>

<style lang="scss" scoped>
.item {
  height: 50px;
  border-bottom: 1px solid #ccc;
  &:nth-child(odd) {
    background-color: #5342b191;
  }
  &:nth-child(even) {
    background-color: #d963638a;
  }
}
</style>
